#include "websocket_handler.h"
#include "message_handler.h"
#include "client_manager.h"
#include <string.h>

// 全局虚拟主机数据
static VHostData vhd_global;
struct lws_protocols protocols[] = {
    {
        "my-protocol",
        ws_callback,
        sizeof(struct per_session_data__custom),
        0, 0, NULL,
    },
    {NULL, NULL, 0, 0, 0, NULL}
};

int ws_callback(struct lws *wsi, enum lws_callback_reasons reason, void *user, void *in, size_t len) {
    struct per_session_data__custom *pss = (struct per_session_data__custom *)user;
    VHostData *vhd = &vhd_global;

    switch (reason) {
    case LWS_CALLBACK_PROTOCOL_INIT:
        init_vhost_data(vhd);
        lwsl_info("协议初始化成功\n");
        break;

    case LWS_CALLBACK_ESTABLISHED:
        if (!init_client_session(pss, wsi, vhd)) return -1;
        break;

    case LWS_CALLBACK_CLOSED:
        handle_connection_closed(pss, vhd, wsi);
        break;

    case LWS_CALLBACK_RECEIVE:
        if (vhd && pss->client && len > 0) {
            handle_received_message(wsi, pss, vhd, in, len);
        }
        break;

    default:
        break;
    }

    return 0;
}